const { ipcRenderer } = require('electron');

// 获取DOM元素
const statusDot = document.getElementById('status-dot');
const statusText = document.getElementById('status-text');
const userInfoForm = document.getElementById('user-info-form');
const startShareBtn = document.getElementById('start-share-btn');
const stopShareBtn = document.getElementById('stop-share-btn');
const shareInfo = document.getElementById('share-info');
const shareUrl = document.getElementById('share-url');
const clientCount = document.getElementById('client-count');
const copyUrlBtn = document.getElementById('copy-url-btn');
const closeShareBtn = document.getElementById('close-share-manager');

// 添加分享按钮
const shareToWeChatBtn = document.getElementById('share-to-wechat');
const shareToDingTalkBtn = document.getElementById('share-to-dingtalk');
const shareToDouyinBtn = document.getElementById('share-to-douyin');
const shareToKuaishouBtn = document.getElementById('share-to-kuaishou');

// 初始化
window.addEventListener('DOMContentLoaded', () => {
    // 请求获取分享状态
    ipcRenderer.send('get-share-status');
    
    // 尝试加载已保存的个人信息
    const savedSettings = localStorage.getItem('widgetSettings');
    if (savedSettings) {
        const settings = JSON.parse(savedSettings);
        
        // 如果设置中存在分享信息，则填充到表单中
        if (settings.shareInfo) {
            if (settings.shareInfo.name) {
                document.getElementById('user-name').value = settings.shareInfo.name;
            }
            if (settings.shareInfo.department) {
                document.getElementById('user-department').value = settings.shareInfo.department;
            }
            if (settings.shareInfo.position) {
                document.getElementById('user-position').value = settings.shareInfo.position;
            }
        }
    }
});

// 快速分享按钮事件处理
function shareToPlatform(platformName, platformUrl) {
    const url = shareUrl.textContent;
    if (!url) {
        alert('请先开始分享，获取分享链接');
        return;
    }
    
    const shareText = `查看我的工位状态和任务进度：${url}`;
    
    // 创建分享数据
    const shareData = {
        title: '桌面挂件分享',
        text: shareText,
        url: url
    };
    
    // 尝试使用 Web Share API
    if (navigator.share) {
        navigator.share(shareData)
            .then(() => console.log('分享成功'))
            .catch(err => console.log('分享失败:', err));
    } else {
        // 降级处理：复制到剪贴板并提示用户
        navigator.clipboard.writeText(shareText).then(() => {
            alert(`${platformName}分享链接已复制到剪贴板，请打开${platformName}粘贴分享`);
        }).catch(() => {
            // 如果剪贴板API不可用，使用选择文本的方式
            const textArea = document.createElement('textarea');
            textArea.value = shareText;
            document.body.appendChild(textArea);
            textArea.select();
            document.execCommand('copy');
            document.body.removeChild(textArea);
            alert(`${platformName}分享链接已复制到剪贴板，请打开${platformName}粘贴分享`);
        });
    }
}

if (shareToWeChatBtn) {
    shareToWeChatBtn.addEventListener('click', () => {
        shareToPlatform('微信', 'weixin://');
    });
}

if (shareToDingTalkBtn) {
    shareToDingTalkBtn.addEventListener('click', () => {
        shareToPlatform('钉钉', 'dingtalk://');
    });
}

if (shareToDouyinBtn) {
    shareToDouyinBtn.addEventListener('click', () => {
        shareToPlatform('抖音', 'snssdk1128://');
    });
}

if (shareToKuaishouBtn) {
    shareToKuaishouBtn.addEventListener('click', () => {
        shareToPlatform('快手', 'kwai://');
    });
}

// 监听从主进程发送的分享状态
ipcRenderer.on('share-status', (event, data) => {
    updateShareStatus(data);
});

// 更新分享状态显示
function updateShareStatus(data) {
    if (data.isSharing && data.serverInfo) {
        // 分享中
        statusDot.classList.add('active');
        statusText.textContent = '分享中';
        startShareBtn.disabled = true;
        stopShareBtn.disabled = false;
        
        // 显示分享信息
        shareInfo.style.display = 'block';
        shareUrl.textContent = data.serverInfo.url;
        // clientCount.textContent = data.serverInfo.clientCount || 0;
    } else {
        // 未分享
        statusDot.classList.remove('active');
        statusText.textContent = '未分享';
        startShareBtn.disabled = false;
        stopShareBtn.disabled = true;
        
        // 隐藏分享信息
        shareInfo.style.display = 'none';
    }
}

// 开始分享
startShareBtn.addEventListener('click', () => {
    const userInfo = {
        name: document.getElementById('user-name').value,
        department: document.getElementById('user-department').value,
        position: document.getElementById('user-position').value
    };
    
    if (!userInfo.name) {
        alert('请输入姓名');
        return;
    }
    
    ipcRenderer.send('start-sharing', userInfo);
});

// 停止分享
stopShareBtn.addEventListener('click', () => {
    if (confirm('确定要停止分享吗？')) {
        ipcRenderer.send('stop-sharing');
    }
});

// 复制链接
copyUrlBtn.addEventListener('click', () => {
    const url = shareUrl.textContent;
    navigator.clipboard.writeText(url).then(() => {
        alert('链接已复制到剪贴板');
    }).catch(err => {
        console.error('复制失败:', err);
        // 降级方案：选择文本
        const range = document.createRange();
        range.selectNode(shareUrl);
        window.getSelection().removeAllRanges();
        window.getSelection().addRange(range);
        document.execCommand('copy');
        window.getSelection().removeAllRanges();
        alert('链接已复制到剪贴板');
    });
});

// 关闭窗口
closeShareBtn.addEventListener('click', () => {
    ipcRenderer.send('close-share-manager');
});

// 监听分享开始
ipcRenderer.on('sharing-started', (event, serverInfo) => {
    updateShareStatus({
        isSharing: true,
        serverInfo: serverInfo
    });
    alert('分享已开始，其他用户可以通过以下地址访问您的信息：' + serverInfo.url);
});

// 监听分享停止
ipcRenderer.on('sharing-stopped', () => {
    updateShareStatus({
        isSharing: false,
        serverInfo: null
    });
    alert('分享已停止');
});

// 监听分享错误
ipcRenderer.on('sharing-error', (event, errorMessage) => {
    alert('分享失败：' + errorMessage);
});